package info.niwota.ispy;

import info.niwota.ispy.Detect.DetectTest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * 
 * @author qiangli
 *
 */
public class MainActivity extends Activity {

    private class DetectTask extends AsyncTask<Void, Void, Void> {

        @Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			
			updateUI();
			
			updateToggle();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			super.onProgressUpdate(values);
		}

		@Override
        protected void onPreExecute() {
            super.onPreExecute();
            //
            ProgressBar pb = (ProgressBar) findViewById(R.id.progress);
            pb.setVisibility(View.VISIBLE);
            
            TextView summary = (TextView) findViewById(R.id.summary);
            summary.setVisibility(View.INVISIBLE);
            
            View scroll = findViewById(R.id.scrollView);
            scroll.setVisibility(View.GONE);
            
            View toggle = findViewById(R.id.ciq_toggle);
            toggle.setVisibility(View.GONE);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            //
            ProgressBar pb = (ProgressBar) findViewById(R.id.progress);
            pb.setProgress(0);
            pb.setVisibility(View.INVISIBLE);
        }

		@Override
		protected Void doInBackground(Void... params) {
			try {
				detect();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}


    }

	private DetectTask task;
	private Detect detect;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Intent intent = getIntent();
        boolean b = intent.getBooleanExtra("extra.startup", false);
        if (b) {
        	if (!Preferences.getRunningStatus(this)) {
        		finish();
        	}
        } else {
        	setRunningStatus(true);
        }
        
        initRes();
    }
    
	private void detect() {
        detect = new Detect();
        detect.findEverything(this);
        //detect.dumpFoundInLogcat();
	}

	private void updateUI() {
		final int score = (detect != null ? detect.getDetectionScore() : 0);
        TextView summary = (TextView) findViewById(R.id.summary);
        if (score == 0) {
            summary.setText(R.string.ciq_not_found);
            summary.setTextColor(Color.GREEN);
            summary.setCompoundDrawablesWithIntrinsicBounds(R.drawable.status_clear, 0, 0, 0);
        } else if (detect.getFound().get(DetectTest.RUNNING_PROCESSES).size() > 0) {
            summary.setText(R.string.ciq_found_active);
            summary.setTextColor(Color.RED);
            summary.setCompoundDrawablesWithIntrinsicBounds(R.drawable.status_alert, 0, 0, 0);
        } else {
            summary.setText(R.string.ciq_found_inactive);
            //summary.setTextColor(Color.YELLOW);
            summary.setTextColor(Color.RED);
            summary.setCompoundDrawablesWithIntrinsicBounds(R.drawable.status_alert, 0, 0, 0);
        }
        summary.setVisibility(View.VISIBLE);

		View scroll = findViewById(R.id.scrollView);
		scroll.setVisibility(View.VISIBLE);
          
        LinearLayout details = (LinearLayout) findViewById(R.id.details_list);
        details.removeAllViews();

        for (DetectTest test : detect.getFound().keySet()) {
        	int cnt = detect.getFound().get(test).size(); 
            if (cnt > 0) {
            	TextView title = new TextView(this);
                
                title.setText(test.name);
                title.setPadding(8, 8, 8, 8);
                title.setTextSize(20);
                title.setTextColor(Color.WHITE);
                details.addView(title);
                //
                for (String line : detect.getFound().get(test)) {
                    TextView content = new TextView(this);
                    content.setText(line);
                    content.setPadding(8, 0, 8, 0);
                    details.addView(content);
                }
            } 
//            else {
//                TextView content = new TextView(this);
//                content.setText("Nothing found");
//                content.setPadding(8, 0, 8, 0);
//                details.addView(content);
//            }
        }
        
        ProgressBar pb = (ProgressBar) findViewById(R.id.progress);
        pb.setVisibility(View.GONE);
        
	}

	private void initRes() {
		final Context ctx = this;
		final Button toggle = (Button) findViewById(R.id.ciq_toggle);
		toggle.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				boolean b = !Utils.isCIQLoggingEnabled(ctx);
				Utils.toggleCIQLogging(ctx, b);
				setText(toggle, b);
				refresh();
			}
		});
	}
	
	private void updateToggle() {
		final Context ctx = this;
		final Button toggle = (Button) findViewById(R.id.ciq_toggle);
		if (Utils.hasCIQLogging(ctx)) {
			toggle.setVisibility(View.VISIBLE);
	        boolean enabled = Utils.isCIQLoggingEnabled(ctx);
	    	setText(toggle, enabled);
		} else {
			toggle.setVisibility(View.GONE);
		}
	}

    private void setText(Button toggle, boolean enabled) {
        toggle.setText(enabled ? "Disable CIQ logging" : "Enable CIQ logging");
    }
    
    
	@Override
	protected void onPause() {
		super.onPause();
		
		if (task != null) {
			task.cancel(true);
		}
		task = null;
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		Notifications.update(this); //reset to default
		
		refresh();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_options, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.main_help_opt_menu_id:
			doHelp();
			return true;
		case R.id.main_settings_opt_menu_id:
			doSettings();
			return true;
		case R.id.main_refresh_opt_menu_id:
			refresh();
			return true;
		case R.id.main_clearlog_opt_menu_id:
			doClearLog();
			return true;
		case R.id.main_quit_opt_menu_id:
			doQuit();
			return true;
		default:
		}
		return false;
	}
	
	private void refresh() {
		try {
			if (task != null) {
				task.cancel(true);
			}

			task = new DetectTask();
			task.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doClearLog() {
		Utils.logcatClear();
		
		refresh();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// cancel only
			finish();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private void doQuit() {
		setRunningStatus(false);
		//
		finish();
	}
	
	private void setRunningStatus(boolean b) {
		final Context ctx = this;
		if (b) {
			Preferences.updateRunningStatus(ctx, true);
			Notifications.add(ctx);
			
			MonitorService.startup(this);
		} else {
			Preferences.updateRunningStatus(ctx, false);
			Notifications.remove(ctx);
			
			MonitorService.shutdown(ctx);
		}
	}
	
	private void doHelp() {
		WebViewActivity.help(this);
	}
	
	private void doSettings() {
		try {
			Intent i = new Intent(this, SettingsActivity.class);
			startActivity(i);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}